package 力扣;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author yyq
 * @create 2022-06-07 16:07
 */
public class leetcode1005 {
    public static void main(String[] args) {
        leetcode1005 leetcode1005=new leetcode1005();
        System.out.println(leetcode1005.largestSumAfterKNegations(new int[]{8,-7,-3,-9,1,9,-6,-9,3
        }, 8));
    }
    public int largestSumAfterKNegations(int[] nums, int k) {
        int fushu=0;
        int zero =0;
        int sum=0;
        Arrays.sort(nums);
        for (int i= 0;i<nums.length;i++){
            if(nums[i]>0) break;
            if(nums[i]==0) zero=1;
            if(nums[i]<0) fushu++;
        }
        if(fushu==0){
            if(zero!=0){
                sum =getTheSum(nums,0,nums.length);
            }
            if(zero==0){
                int z = k%2;
                if(z==0){
                    sum =getTheSum(nums,0,nums.length);
                }
                if(z==1){

                    sum =getTheSum(nums,1,nums.length) - nums[0];
                }
            }
        }
        if(fushu!=0){
            if(k>fushu){
                if(zero!=0){
                    sum =-getTheSum(nums,0,fushu) + getTheSum(nums,fushu,nums.length);
                }
                if(zero==0){
                    int z=(k-fushu)%2;
                    if(z==0){
                        sum = -getTheSum(nums,0,fushu) + getTheSum(nums,fushu, nums.length );
                    }
                    if(z==1){
                        if(-nums[fushu-1]>nums[fushu]){
                            sum = -getTheSum(nums,0,fushu)+getTheSum(nums,fushu,nums.length)-nums[fushu]*2;
                        }
                        else     sum = -getTheSum(nums,0,fushu-1) + getTheSum(nums,fushu-1,nums.length) ;
                    }
                }
            }
            if(k<=fushu){
                sum = -getTheSum(nums,0,k)+getTheSum(nums,k,fushu)+getTheSum(nums,fushu,nums.length);
            }
        }
        return sum;
    }

    public int getTheSum(int[] nums,int begin,int end){
        int sum = 0;
        for (int i =begin;i<end;i++){
            sum = sum + nums[i];
        }
        return sum;
    }
}
